package com.inight.ojcodesandbox.controller;


import cn.hutool.core.util.StrUtil;
import com.inight.ojcodesandbox.JavaNativeCodeSandbox;
import com.inight.ojcodesandbox.model.ExecuteCodeRequest;
import com.inight.ojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
//@Controller
//@ResponseBody 不加这个会 404
public class MainController {

    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "ying";

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;


    @GetMapping("get")
    public String get() {
        return "Hello World";
    }

    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest
    , HttpServletRequest request, HttpServletResponse response) {
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if(StrUtil.isBlank(header)) {
            // 设置 403 禁止访问, 直接返回 null
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }

}
